<template>
  <fieldset>
    <legend>失效函数的应用</legend>
    <h1 id="content">{{ content }}</h1>
    <button
      v-for="(btn, index) in buttons"
      :key="index"
      @click="pageChange(index + 1)"
      :class="{ active: index + 1 === page }"
    >
      {{ btn }}
    </button>
  </fieldset>
</template>
<script setup>
import CancelPromise from "./cancelPromise";
import { ref, onMounted, reactive, watchEffect } from "vue";
let buttons = reactive(["第1页", "第2页", "第3页"]);
let api1 = (signal) =>
  new CancelPromise((resolve, reject) => {
    setTimeout(() => {
      resolve("第一页的数据");
    }, 1000);
  }, signal);
let api2 = (signal) =>
  new CancelPromise((resolve, reject) => {
    setTimeout(() => {
      resolve("第二页的数据");
    }, 1500);
  }, signal);
let api3 = (signal) =>
  new CancelPromise((resolve, reject) => {
    setTimeout(() => {
      resolve("第三页的数据");
    }, 2000);
  }, signal);
let api = {
  api1,
  api2,
  api3,
};
let content = ref("");
let page = ref(1);
//封装获取内容的方法
/**
 *
 * @param {Number} pageSize 传递给后台的页码
 * @param {Object} signal 控制器（AbortController）的signal对象
 */
let fetchData = (pageSize = 1, signal) =>
  api["api" + pageSize](signal).then((res) => {
    console.log(res);
    content.value = res;
  });
let pageChange = (pageSize) => {
  page.value = pageSize;
};
// onMounted(() => {
//   fetchData();
// });
//监控page.value
watchEffect((onInvalidate) => {
  let abortController = new AbortController();
  let signal = abortController.signal;
  fetchData(page.value, signal);
  onInvalidate(() => {
    abortController.abort();
  });
});
</script>

<style scoped>
.active {
  background-color: hotpink;
}
</style>
